package com.yunsc.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunsc.common.exception.YunscException;
import com.yunsc.common.utils.PageResult;
import com.yunsc.store.dao.YunscCouponDao;
import com.yunsc.store.dao.YunscUserCouponDao;
import com.yunsc.store.dto.CouponParamDTO;
import com.yunsc.store.entity.YunscCouponEntity;
import com.yunsc.store.service.YunscCouponService;
import com.yunsc.store.service.YunscUserService;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;


@Service("yunscCouponService")
public class YunscCouponServiceImpl extends ServiceImpl<YunscCouponDao, YunscCouponEntity> implements YunscCouponService {

    @Resource
    private YunscUserCouponDao userCouponDao;
    @Resource
    private YunscUserService userService;


    @Override
    public List<YunscCouponEntity> queryPageCouponList(Integer userId, Integer showNum, Integer storeId) {
        LambdaQueryWrapper<YunscCouponEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscCouponEntity::getIsDelete, 0);
        lqw.eq(YunscCouponEntity::getStatus, 1);
        lqw.orderByDesc(YunscCouponEntity::getCreateTime);
        Page<YunscCouponEntity> pageResult = this.page(new Page<>(1, showNum), lqw);
        List<YunscCouponEntity> couponEntityList = pageResult.getRecords();
        if (CollectionUtils.isEmpty(couponEntityList) ){
            return new ArrayList<>();
        }
        return getCouponStateList(userId, couponEntityList);

    }

    @Override
    public List<YunscCouponEntity> queryCouponList(Integer userId, Integer storeId) {
        LambdaQueryWrapper<YunscCouponEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscCouponEntity::getStoreId, storeId);
        lqw.eq(YunscCouponEntity::getIsDelete, 0);
        lqw.eq(YunscCouponEntity::getStatus, 1);
        lqw.orderByDesc(YunscCouponEntity::getCreateTime);
        List<YunscCouponEntity> couponEntityList = this.list(lqw);
        return getCouponStateList(userId, couponEntityList);
    }

    @Override
    public PageResult<YunscCouponEntity> queryCouponPageList(CouponParamDTO param, Integer storeId) {
        LambdaQueryWrapper<YunscCouponEntity> lqw = new LambdaQueryWrapper<>();
        lqw.eq(YunscCouponEntity::getStoreId, storeId);
        lqw.eq(YunscCouponEntity::getIsDelete, 0);
        lqw.like(StringUtils.isNotEmpty(param.getSearch()), YunscCouponEntity::getName, param.getSearch());
        lqw.orderByDesc(YunscCouponEntity::getSort);
        Page<YunscCouponEntity> couponEntityPage = this.page(new Page<>(param.getPage(), param.getPageSize()), lqw);
        List<YunscCouponEntity> couponEntityList = couponEntityPage.getRecords();

        return PageResult.formatPageResult(couponEntityList, param.getPage(), param.getPageSize(), couponEntityPage.getTotal());

    }

    @Override
    public void addCoupon(CouponParamDTO param, Integer storeId) {
        YunscCouponEntity coupon = param.getForm();
        Integer expireType = coupon.getExpireType();
        if (expireType == 20){
            List<String> betweenTime = coupon.getBetweenTime();
            DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
            long startTime = ZonedDateTime.parse(betweenTime.get(0), formatter).toInstant().toEpochMilli() / 1000;
            long endTime = ZonedDateTime.parse(betweenTime.get(1), formatter).toInstant().toEpochMilli() / 1000;
            coupon.setStartTime(Math.toIntExact(startTime));
            coupon.setEndTime(Math.toIntExact(endTime));
        }
        // 适用范围(10全部商品 20指定商品 30排除商品)
        if (coupon.getApplyRange() == 20){
            // 指定商品
            coupon.setApplyRangeConfig(JSON.toJSONString(coupon.getApplyRangeConfig()));
        }
        coupon.setStoreId(storeId);
        this.save(coupon);
    }

    @Override
    public void editCoupon(CouponParamDTO param) {
        YunscCouponEntity coupon = this.getById(param.getCouponId());
        if (coupon == null){
            throw new YunscException("优惠券不存在");
        }
        YunscCouponEntity form = param.getForm();
        BeanUtils.copyProperties(form, coupon);
        coupon.setCouponId(coupon.getCouponId());
        Integer expireType = form.getExpireType();
        if (expireType == 20){
            List<String> betweenTime = form.getBetweenTime();
            DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
            int startTime = (int) (ZonedDateTime.parse(betweenTime.get(0), formatter).toInstant().toEpochMilli() / 1000);
            int endTime = (int) (ZonedDateTime.parse(betweenTime.get(1), formatter).toInstant().toEpochMilli() / 1000);
            coupon.setStartTime(startTime);
            coupon.setEndTime(endTime);
        }
        // 适用范围(10全部商品 20指定商品 30排除商品)
        if (form.getApplyRange() == 20){
            // 指定商品
            coupon.setApplyRangeConfig(JSON.toJSONString(form.getApplyRangeConfig()));
        }

        this.updateById(coupon);
    }

    @Override
    public void deleteCoupon(CouponParamDTO param) {
        YunscCouponEntity coupon = this.getById(param.getCouponId());
        if (coupon == null) {
            throw new YunscException("优惠券不存在");
        }
        coupon.setIsDelete(1);
        this.updateById(coupon);
    }

    @Override
    public YunscCouponEntity queryCouponDetail(Integer couponId) {
        YunscCouponEntity coupon = this.getById(couponId);
        if (coupon == null){
            throw new YunscException("优惠券不存在");
        }
        if (coupon.getApplyRange() == 20){
            // 指定商品
            coupon.setApplyRangeConfig(JSON.parseObject((String) coupon.getApplyRangeConfig()));
        }

        return coupon;
    }


    @NotNull
    private List<YunscCouponEntity> getCouponStateList(Integer userId, List<YunscCouponEntity> couponEntityList) {
        List<Integer> couponIds;
        if (userId != null){
            couponIds = userCouponDao.selectUserCouponId(userId);
        } else {
            couponIds = Collections.emptyList();
        }
        for (YunscCouponEntity couponEntity : couponEntityList) {
            if (couponIds.contains(couponEntity.getCouponId())){
                Map<String, Object> state = new HashMap<>();
                state.put("text", "已领取");
                state.put("value", 0);
                couponEntity.setState(state);
            }else{
                Map<String, Object> state = new HashMap<>();
                state.put("text", "领取");
                state.put("value", 1);
                couponEntity.setState(state);
            }
        }
        return couponEntityList;
    }
}